package com.engine.action;

import com.engine.core.domain.CustomQuery;
import com.engine.core.util.QueryUtil;
import com.engine.core.util.Response;
import com.engine.service.CustomService;
import com.engine.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/custom/db")
public class CustomAction{

    @Autowired
    private CustomService customService;

    @RequestMapping  (value="/id/{queryId}", method = {RequestMethod.GET,RequestMethod.POST})
    public String queryId(@PathVariable("queryId")  int queryId, HttpServletRequest request,HttpServletRequest response){
        Map<String,Object> params=QueryUtil.request2Map(request);
        CustomQuery customQuery= customService.getCustomQuery(queryId,null,null);
        Response result = customService.queryById(customQuery,new User(),params);
        return result.getJSONString();
    }

    @RequestMapping  (value="/name/{queryName}/{resourceNamespace}", method = {RequestMethod.GET,RequestMethod.POST})
    public String queryName(@PathVariable("queryName")  String queryName,@PathVariable("resourceNamespace") String resourceNamespace, HttpServletRequest request,HttpServletRequest response){
        Map<String,Object> params=QueryUtil.request2Map(request);
        CustomQuery customQuery= customService.getCustomQuery(-1,queryName,resourceNamespace);
        Response result = customService.queryById(customQuery,new User(),params);
        return result.getJSONString();
    }

    @PutMapping("/name/{queryName}/{resourceNamespace}")
    public String updateId(@PathVariable("queryName")  String queryName,@PathVariable("resourceNamespace") String resourceNamespace, HttpServletRequest request,HttpServletRequest response){
        Map<String,Object> params=QueryUtil.request2Map(request);
        CustomQuery customQuery= customService.getCustomQuery(-1,queryName,resourceNamespace);
        Response result = customService.saveOrUpdateById(customQuery,new User(),params);

        return result.getJSONString();
    }

    @PutMapping("/name/{queryId}")
    public String updateName(@PathVariable("queryId")  int queryId, HttpServletRequest request,HttpServletRequest response){
        Map<String,Object> params=QueryUtil.request2Map(request);
        CustomQuery customQuery= customService.getCustomQuery(queryId,null,null);
        Response result = customService.saveOrUpdateById(customQuery,new User(),params);
        return result.getJSONString();
    }

    @PostMapping("/build/{tableName}")
    public String build(@PathVariable("tableName")  String tableName, HttpServletRequest request,HttpServletRequest response){
        Map<String,Object> params=QueryUtil.request2Map(request);
        Response result = customService.customBasicBuild(tableName);
        return result.getJSONString();
    }

}
